import { reactive } from "vue";
//校验函数
//校验验证['常规']
const validateCapture = (rule, value, callback) => {
  if (!isNaN(value) || value === "") {
    callback(new Error("输入值不能为空也不能为数字哦"));
  } else {
    if (value.length < 5) {
      callback(new Error("验证码小于五位,程序进入休眠状态"));
    } else {
      callback();
    }
  }
};
//校验用户名['常规']
const validateUsername = (rule, value, callback) => {
  var uPattern = /^[a-zA-Z0-9_-]{3,16}$/;
  let backRules = uPattern.test(value);
  if (!backRules) {
    callback(new Error("你已经违反了用户名输入格式"));
  } else {
    callback();
  }
};
//校验密码['常规']
const validatePassword = (rule, value, callback) => {
  if (value) {
    callback();
  } else {
    callback(new Error("你的密码有误程序即将自动销毁"));
  }
};

//校验规则['常规']
export const loginRules = reactive({
  username: [{ validator: validateUsername, trigger: "blur" }],
  password: [{ validator: validatePassword, trigger: "blur" }],
  captcha: [{ validator: validateCapture, trigger: "blur" }],
});
//校验手机号['手机登入']
const validatePhone = (rule, value, callback) => {
  var iphone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
  let backIpnoe = iphone.test(value);
  if (!backIpnoe) {
    callback(new Error("手机号格式有误"));
  } else {
    callback();
  }
};
//校验验证码['手机登入']
const validatephoneverification = (rule, value, callback) => {
  if (value) {
    callback();
  } else {
    callback(new Error("请输入手机验证码"));
  }
};
//校验手机登入['手机登入']
export const phoneRules = reactive({
  phone: [{ validator: validatePhone, trigger: "blur" }],
  phoneverification: [
    { validator: validatephoneverification, trigger: "blur" },
  ],
});
//表单提交的时候
/**
 *['常规']
 * @param {Object} formEl 表单的引用对象
 * @param {Function} successCallback 表单校验通过的回调函数
 * @param {Function} faildCallback  表单校验失败的回调函数
 */
export const useSubmitForm = (successCallback, faildCallback) => (formEl) => {
  //console.log(formEl)
  if (!formEl) return;
  //调用了组件提供的校验的方法
  formEl.validate((valid) => {
    // 如果所有的表单校验通过,valid就是true,不然就是false
    if (valid) {
      //登入请求可以在这里发送
      successCallback();
      // console.log('submit!')
    } else {
      // console.log('error submit!')
      faildCallback(false);
      return false;
    }
  });
};
